package com.sun.showcase.exception;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import com.sun.showcase.biz.exception.BusinessException;
import com.sun.showcase.pojo.Result;

@RestControllerAdvice
public class GlobalExceptionHandler {
	
	private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
    public static final String DEFAULT_ERROR_VIEW = "exception";
    
    public static final String DEFAULT_ERROR_MSG = "系统异常！";
    
    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
    	
    	Result r = new Result();
    	
    	r.setSuccess(false);
    	
    	r.setMsg(e.getMessage());
    	
    	logger.info("系统异常,{}",e.getMessage());
    	
    	if(logger.isDebugEnabled()){
    		e.printStackTrace();
    	}
    	
        return r;
    }
    
    

    @ResponseBody
	@ExceptionHandler(value = BusinessException.class)
	public Result businessException(BusinessException e,WebRequest request){
		
    	Result result = new Result();
		
    	result.setSuccess(false);
		result.setMsg(e.getMessage());
		
		return result;
	}
    
    @ExceptionHandler(value = DefaultException.class)
    public Result defaultExceptionHandler(DefaultException e) throws Exception {
    	logger.error("DefaultException,{},{},{}",e.getMessage(),e.getCode(),e.getMsg());
    	Result r = new Result();
    	r.setSuccess(false);
    	r.setMsg(e.getMsg());
    	r.setCode(String.valueOf(e.getCode()));
        return r;
    }
}
